#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
//#include <unistd.h>
#include <sys/types.h>
//#include <sys/time.h>
#include <sys/file.h>
//#include <sys/stat.h>
//#include <dirent.h>
//#include <ctype.h>
//#include <fcntl.h>
//#include <dlfcn.h>
//#include <sstream>
#include <fstream>
#include <iostream>
//#include <assert.h>
//#include <iostream>
//#include <unistd.h>
//#include <sys/wait.h>
#include <errno.h>
#include "config.h"
//#include "debug.h"

bool Configure::_confInfo(string stemp)
{
        size_t idx = stemp.find('=', 0);
	if(idx>0 && idx < stemp.length())
	{	
		string key = stemp.substr(0, idx);
                trim(key);
		string val = stemp.substr(idx + 1, stemp.length()- idx -1);
	        trim(val); 
		m_Confs[key] = val;
	}
	else
	{
	} 
	return true;
}

void Configure :: trim(string& str)
{
   string::size_type pos = str.find_last_not_of(' ');
   if(pos != string::npos)
   {
      str.erase(pos + 1);
      pos = str.find_first_not_of(' ');
      if(pos != string::npos) str.erase(0, pos);
   }
   else str.erase(str.begin(), str.end());
}

map <string, string > Configure::LoadConfInfo(const char *fn)
{
	m_Confs.clear();
	if(fn != NULL)
		_explainFile(fn);
	return m_Confs;
}

bool Configure::_explainFile(const char *fn)
{
	ifstream infs(fn);
	if (!infs) {
		return false;
	}
	int lineNum=0;
	int commentLevel = 0;
	string line;
	while (getline(infs, line))
	{
		++lineNum;
		string stemp = line;
		int index;
		int lastLoc = 0;
		while (true) {
			index = (int) stemp.find('#', lastLoc) ;
			if (index != -1) {
				if (index > 0 && line[index-1] == '\\') {
					lastLoc = index+1;
					continue;
				} else {
					stemp = stemp.substr(0,index);
					break;
				}
			} else {
				break;
			}
		}

		if (stemp.length() == 0) {
			continue;
		}

		string sa, sb;
		if(stemp.length()>2)
		{
			sa = stemp.substr(0, 2);
			sb = stemp.substr(stemp.length()-2,2);
		}
		else if(stemp.length() == 2)
		{
			sa = stemp;
			sb = stemp;
		}

		if (sa == "/*") {
			++commentLevel;
			continue;
		}

		if (sb == "*/") {
			if (commentLevel == 0) {
				cerr <<  lineNum << ": extra close comment\n";
				return false;
			} else {
				--commentLevel;
			}
			continue;
		}
		if (commentLevel > 0) {
			continue;
		}
                _confInfo(stemp);    
	}
	if(m_Confs.size() > 0)
		return true;
	return false;
}
void Configure::Print()
{
	cout<<" ========== conf ============= "<<endl;
	map <string , string >::iterator iter;
	for(iter=m_Confs.begin(); iter != m_Confs.end(); iter++)
	{
             cout<< iter->first.c_str()<<"="<<iter->second.c_str()<<endl;
	}
}

